package InternetCode.Exa3;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.InetAddress;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * 获得所在局域网所有的ip地址
 */
public class CoreCode {

    private static volatile int num = 0;

    public static void main(String[] args) throws IOException {
        System.out.println("稍等片刻,正在扫描: ");
        List<String> result = getAllIp();
        System.out.println("扫描完成,打印地址");
        System.out.println(result);
    }

    /**
     * 获得内网所有的可通信的ip地址
     * @return
     * @throws IOException
     */
    public static List<String> getAllIp() throws IOException {
        InetAddress host=InetAddress.getLocalHost();
        String hostAddress=host.getHostAddress();
        int pos=hostAddress.lastIndexOf(".");

        //获得本机ip的网段
        String bigNet=hostAddress.substring(0,pos+1);
        List<String> ips= Collections.synchronizedList(new ArrayList<>());
        for (int i=0;i<=225;i++){
            String ip=bigNet+i;
            new Thread(()->{
                try {
                    Process process = Runtime.getRuntime().exec("ping "+ip+" -w 280 -n 1");
                    InputStream inputStream=process.getInputStream();
                    InputStreamReader inputStreamReader=new InputStreamReader(inputStream,"GBK");
                    BufferedReader bufferedReader=new BufferedReader(inputStreamReader);
                    String line=null;
                    String isActive=null;
                    while((line=bufferedReader.readLine()) != null) {
                        if(!line.equals("")){
                            isActive=bufferedReader.readLine().substring(0,2);
                            break;
                        }
                    }
                    if(isActive.equals("来自")){
                        ips.add(ip);
                    }
                }catch (Exception e){
                    e.printStackTrace();
                }
                num++;
            }).start();
        }
        while (num!=225) {}
        return ips;
    }
}
